package net.wisos.opn.search;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrResourceLoader;
import org.xml.sax.SAXException;

public class EmbeddedServerContainer {
	Logger logger = Logger.getLogger(EmbeddedServerContainer.class);
	private static CoreContainer container;
	private String solrHome;

	public EmbeddedServerContainer(String solrHome)
			throws ParserConfigurationException, IOException, SAXException {
		setSolrHome(solrHome);
		File f = new File(getSolrHome(), "solr.xml");
		container = new Initializer().initialize();
		container.load(getSolrHome(), f);
		container.setPersistent(true);
		logger.info("启动搜索server完成！");
	}

	public void shutdown() {
		if (container == null)
			throw new SearchServerException("不能关闭搜索server,server容器为空!!!");
		if (container.isPersistent())
			container.persist();
		container.shutdown();
		logger.info("搜索server关闭!");
	}

	public synchronized void persite() {
		if (container == null)
			throw new SearchServerException("持久化错误,Server容器不能为空!!!");
		container.persist();
		logger.info("搜索server持久化完成！");
	}

	public synchronized void addCore(String solrName, String instanceDir,
			boolean isPersist) throws ParserConfigurationException,
			IOException, SAXException {
		CoreDescriptor p = new CoreDescriptor(container, solrName, instanceDir);
		SolrCore core = container.create(p);
		container.register(solrName, core, false);
		if (isPersist)
			container.persist();
	}

	public SolrServer getSolrCore(String solrName) {
		if (container.getCoreNames().contains(solrName))
			return new EmbeddedSolrServer(container, solrName);
		return null;
	}

	static class Initializer extends CoreContainer.Initializer {
		public Initializer() {
		}

		@Override
		public CoreContainer initialize() {
			return new CoreContainer(new SolrResourceLoader(
					SolrResourceLoader.locateSolrHome()));
		}

	}

	public CoreContainer getContainer() {
		return container;
	}

	public String getSolrHome() {
		return solrHome;
	}

	public void setSolrHome(String searchServerHome) {
		this.solrHome = searchServerHome;
	}

}
